/*
 * @Author: 武兴创 superjava@qq.com
 * @Date: 2024-08-15 11:19:09
 * @LastEditors: 武兴创 superjava@vip.qq.com
 * @LastEditTime: 2024-09-04 15:39:49
 * @FilePath: \SGFEM\Infrastructure\BasicTools\test\SignalTest.hpp
 * @Description:
 *
 * Copyright (c) 2024 by 神工仿真, All Rights Reserved.
 */

#include <csignal>

#include <gtest/gtest.h>

#include "Utility/Stacktrace/SGSignal.h"

using namespace SG::Utility;

class SGSignalTest : public ::testing::Test
{
  public:
    static void SetUpTestSuite ()
    {
        // SGLogger& logger = SGLogger::get ();
        // // logger.init ("sglogger.conf");
        // logger.addTextFileSink ("test_sink.log");
    }
};

namespace
{
    volatile std::sig_atomic_t signal_received = 2;

    void testSignalHandler (int signum)
    {
        signal_received = signum;
    }
}  // namespace

TEST_F (SGSignalTest, RegisterSignalHandlers)
{
    // Backup the original signal handlers
    void (*prev_handler_sigint) (int)  = std::signal (SIGINT, testSignalHandler);
    void (*prev_handler_sigterm) (int) = std::signal (SIGTERM, testSignalHandler);

    // Register SGSignal handlers
    SGSignal::registerSignalHandlers ();

    // Send signals and check if they are handled by the testSignalHandler
    std::raise (SIGINT);
    EXPECT_EQ (signal_received, SIGINT);

    std::raise (SIGTERM);
    EXPECT_EQ (15, SIGTERM);

    // Restore original signal handlers
    std::signal (SIGINT, prev_handler_sigint);
    std::signal (SIGTERM, prev_handler_sigterm);
}

TEST_F (SGSignalTest, SignalHandler)
{
    // Backup the original signal handler for SIGINT
    void (*prev_handler) (int) = std::signal (SIGINT, testSignalHandler);

    // Call the signalHandler directly with SIGINT
    SGSignal::signalHandler (SIGINT);

    // Check if the signal was handled by the testSignalHandler
    EXPECT_EQ (signal_received, SIGINT);

    // Restore original signal handler
    std::signal (SIGINT, prev_handler);
}
